<?php

session_start();
require_once '../src/MyDBi.php';
$db = new MysqliDb();

$type = $_POST["type"];

if ($type == 0) {
    // Búsqueda - 0

    $id = $_POST["id"];
    $idreserva = $_POST["idreserva"];

    $sqlWhere = "";

    if ($id != -1) {
        $sqlWhere = "and (IdRegistracion = " . $id . " or (IdRegistracion = -1 and "
                . "IdCliente in (Select IdCliente from registracionesclientes where IdRegistracion = " . $id . "))) ";
    } else {
        $sqlWhere = "and IdReserva = " . $idreserva;
    }

//    $query = $con->selectFrom("movimientos", $columns = null, $where = array("IdRegistracion"=>$id), $like = false, $orderby = null, $direction = "DESC", $limit = null, $offset = null);

    $SQL = "SELECT IdMovimiento, Fecha, IdCuenta, "
            . "CASE WHEN m.IdItem is null then 'NO ITEM' else (SELECT Nombre from items i where m.IdItem = i.IdItem) END as Item, "
            . "Cantidad, "
            . "IdUsuario, "
            . "m.IdCliente IdCliente, "
            . "(Select concat(Nombre, ' ', Apellido) from clientes c where c.IdCliente = m.IdCliente) Cliente, "
            . "Importe, "
            . "Detalles "
            . "from movimientos m where IdCuenta in('4.1.1.06','1.1.1.01','1.1.1.02','1.1.2.01','1.1.2.02','1.1.2.03','4.1.4.01') "
            . "and Importe > 0 " . $sqlWhere;

//    $query = $con->customSelectFrom($SQL);

    $result = $db->rawQuery($SQL);

    $total = 0;
    if ($db->count > 0) {
//        $result = $query["result"];
        foreach ($result as $row) {


            $backMarcado = '';
            if ($row["IdCuenta"] == '1.1.2.01' || $row["IdCuenta"] == '1.1.2.02' || $row["IdCuenta"] == '1.1.2.03') {
                $backMarcado = ' style = "color:red;" ';
                $total = $total + $row['Importe'];
            } else {
                $total = $total - $row['Importe'];
            }

            echo "<tr" . $backMarcado . "><td>" . $row["Fecha"] . "</td>"
            . "<td>" . $row["Cliente"] . "</td><td>" . $row["Detalles"] . "</td>"
            . "<td>" . $row["Item"] . "</td>"
            . "<td style='text-align:center;'>" . $row["Importe"] . "</td></tr>";
        }
        echo '<script type="text/javascript">updateImporteResumen(' . $total . ')</script>';
        echo '<script type="text/javascript">window.IdClienteCobro='.$row["IdCliente"].'</script>';
    } else {
        echo '<tr >'
        . '<td></td>'
        . "<td></td><td></td>"
        . "<td></td><td></td>"
        . "<td></td><td></td>"
        . "<td></td><td></td>"
        . '<td '
        . "style='cursor:pointer;'></td></tr>";
        echo '<script type="text/javascript">updateImporteResumen(0)</script>';
    }
}
?>